#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 1. 修改标题
    this->setWindowTitle("服务器");

    // 2. 创建 QTcpServer 实例
    tcpServer = new QTcpServer(this);

    connect(tcpServer, &QTcpServer::newConnection, this, &Widget::processConnection);

    // 4. 绑定并监听端口号??
    // 这个操作得是最后一步   绑定监听一起做了
    bool ret = tcpServer->listen(QHostAddress::Any, 9090);
    if(!ret) {
        QMessageBox::critical(this, "服务器启动失败!", tcpServer->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    // 1. 通过 tcpServer 拿到一个 socket 对象
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) + "] 客户端上线";
    ui->listWidget->addItem(log);

    // 2. 通过信号槽来处理客户端发来请求的情况
    connect(clientSocket, &QTcpSocket::readyRead, this, [=](){
        // 读取请求数据  readAll 返回的是 QByteArray 通过赋值转化成 QString
        QString request = clientSocket->readAll();
        // 根据请求构建响应
        const QString& response = process(request);
        clientSocket->write(response.toUtf8());
        // 记录到日志中
        QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) + "] " + " req: " + request + ", resp: " + response;
        ui->listWidget->addItem(log);
    });
    // 之前学linux 需要搞一个循环，循环的读取请求，循环的处理
    // qt 中使用信号槽来处理

    // 3. 通过信号槽 处理客户端断开连接的情况
    connect(clientSocket, &QTcpSocket::disconnected, this, [=](){
        QString log = "[" + clientSocket->peerAddress().toString() + ":" + QString::number(clientSocket->peerPort()) + "] 客户端下线";
        ui->listWidget->addItem(log);

        // 手动释放 clientSocket 直接使用 delete 是下策 使用 deleteLater
        // delete clientSocket;
        clientSocket->deleteLater();    // 下一轮事件循环执行 确保槽函数执行完毕了
    });
}

QString Widget::process(const QString request)
{
    return request;
}

